import { defineStore } from 'pinia'
import { scenicApi } from '@/api/scenic'
import { ElMessage } from 'element-plus'

export const useScenicStore = defineStore('scenic', {
  state: () => ({
    // 景区列表数据
    scenics: [],
    // 当前选中的景区
    currentScenic: null,
    // 加载状态
    loading: false,
    // 分页状态
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filterParams: {
      keyword: '', // 搜索关键词（景区名称）
      category: '', // 分类筛选
      status: '', // 状态筛选
      priceRange: [], // 门票价格范围
      dateRange: [] // 创建时间范围
    },
    // 景区分类列表
    categories: [
      { value: 'natural', label: '自然景观' },
      { value: 'cultural', label: '文化古迹' },
      { value: 'modern', label: '现代景点' },
      { value: 'park', label: '公园广场' },
      { value: 'temple', label: '寺庙宗教' },
      { value: 'museum', label: '博物馆' }
    ],
    // 图片上传状态
    uploadLoading: false
  }),

  getters: {
    // 获取活跃景区
    activeScentics: (state) => state.scenics.filter(scenic => scenic.status === 'active'),
    
    // 获取非活跃景区
    inactiveScentics: (state) => state.scenics.filter(scenic => scenic.status === 'inactive'),
    
    // 按分类分组的景区
    scenicsByCategory: (state) => {
      const grouped = {}
      state.scenics.forEach(scenic => {
        const category = scenic.category || 'other'
        if (!grouped[category]) {
          grouped[category] = []
        }
        grouped[category].push(scenic)
      })
      return grouped
    },
    
    // 免费景区
    freeScentics: (state) => state.scenics.filter(scenic => scenic.ticketPrice === 0),
    
    // 收费景区
    paidScentics: (state) => state.scenics.filter(scenic => scenic.ticketPrice > 0),
    
    // 景区统计信息
    scenicStats: (state) => {
      const stats = {
        total: state.scenics.length,
        active: 0,
        inactive: 0,
        free: 0,
        paid: 0,
        byCategory: {}
      }
      
      state.scenics.forEach(scenic => {
        stats[scenic.status] = (stats[scenic.status] || 0) + 1
        
        if (scenic.ticketPrice === 0) {
          stats.free++
        } else {
          stats.paid++
        }
        
        const category = scenic.category || 'other'
        stats.byCategory[category] = (stats.byCategory[category] || 0) + 1
      })
      
      return stats
    }
  },

  actions: {
    // 获取景区列表
    async fetchScentics(params = {}) {
      this.loading = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.filterParams,
          ...params
        }
        
        const response = await scenicApi.getScentics(queryParams)
        this.scenics = response.data || []
        this.pagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取景区列表失败:', error)
        ElMessage.error('获取景区列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建景区
    async createScenic(scenicData) {
      try {
        const response = await scenicApi.createScenic(scenicData)
        
        // 刷新景区列表
        await this.fetchScentics()
        
        ElMessage.success('景区创建成功')
        return response
      } catch (error) {
        console.error('创建景区失败:', error)
        ElMessage.error('创建景区失败')
        throw error
      }
    },

    // 更新景区信息
    async updateScenic(id, scenicData) {
      try {
        const response = await scenicApi.updateScenic(id, scenicData)
        
        // 更新本地景区数据
        const index = this.scenics.findIndex(scenic => scenic.id === id)
        if (index !== -1) {
          this.scenics[index] = { ...this.scenics[index], ...scenicData }
        }
        
        ElMessage.success('景区信息更新成功')
        return response
      } catch (error) {
        console.error('更新景区失败:', error)
        ElMessage.error('更新景区失败')
        throw error
      }
    },

    // 删除景区
    async deleteScenic(id) {
      try {
        await scenicApi.deleteScenic(id)
        
        // 从本地数据中移除景区
        this.scenics = this.scenics.filter(scenic => scenic.id !== id)
        this.pagination.total -= 1
        
        ElMessage.success('景区删除成功')
      } catch (error) {
        console.error('删除景区失败:', error)
        ElMessage.error('删除景区失败')
        throw error
      }
    },

    // 批量删除景区
    async batchDeleteScentics(scenicIds) {
      try {
        await scenicApi.batchDeleteScentics(scenicIds)
        
        // 从本地数据中移除景区
        this.scenics = this.scenics.filter(scenic => !scenicIds.includes(scenic.id))
        this.pagination.total -= scenicIds.length
        
        ElMessage.success(`成功删除 ${scenicIds.length} 个景区`)
      } catch (error) {
        console.error('批量删除景区失败:', error)
        ElMessage.error('批量删除景区失败')
        throw error
      }
    },

    // 上传景区图片
    async uploadScenicImages(files, scenicId = null) {
      this.uploadLoading = true
      try {
        const formData = new FormData()
        
        // 支持多文件上传
        if (Array.isArray(files)) {
          files.forEach(file => {
            formData.append('files', file)
          })
        } else {
          formData.append('files', files)
        }
        
        if (scenicId) {
          formData.append('scenicId', scenicId)
        }
        
        const response = await scenicApi.uploadImages(formData)
        
        ElMessage.success('图片上传成功')
        return response
      } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败')
        throw error
      } finally {
        this.uploadLoading = false
      }
    },

    // 删除景区图片
    async deleteScenicImage(imageId, scenicId) {
      try {
        await scenicApi.deleteImage(imageId)
        
        // 更新本地景区数据，移除图片
        const scenicIndex = this.scenics.findIndex(scenic => scenic.id === scenicId)
        if (scenicIndex !== -1) {
          this.scenics[scenicIndex].images = this.scenics[scenicIndex].images.filter(
            img => img.id !== imageId
          )
        }
        
        ElMessage.success('图片删除成功')
      } catch (error) {
        console.error('删除图片失败:', error)
        ElMessage.error('删除图片失败')
        throw error
      }
    },

    // 更新景区状态
    async updateScenicStatus(id, status) {
      try {
        await scenicApi.updateScenicStatus(id, status)
        
        // 更新本地景区状态
        const index = this.scenics.findIndex(scenic => scenic.id === id)
        if (index !== -1) {
          this.scenics[index].status = status
        }
        
        ElMessage.success('景区状态更新成功')
      } catch (error) {
        console.error('更新景区状态失败:', error)
        ElMessage.error('更新景区状态失败')
        throw error
      }
    },

    // 按分类筛选景区
    async filterByCategory(category) {
      this.filterParams.category = category
      this.pagination.current = 1
      await this.fetchScentics()
    },

    // 按状态筛选景区
    async filterByStatus(status) {
      this.filterParams.status = status
      this.pagination.current = 1
      await this.fetchScentics()
    },

    // 按价格范围筛选景区
    async filterByPriceRange(priceRange) {
      this.filterParams.priceRange = priceRange
      this.pagination.current = 1
      await this.fetchScentics()
    },

    // 搜索景区
    async searchScentics(keyword) {
      this.filterParams.keyword = keyword
      this.pagination.current = 1
      await this.fetchScentics()
    },

    // 综合筛选景区
    async filterScentics(filters) {
      this.filterParams = { ...this.filterParams, ...filters }
      this.pagination.current = 1
      await this.fetchScentics()
    },

    // 重置筛选条件
    resetFilterParams() {
      this.filterParams = {
        keyword: '',
        category: '',
        status: '',
        priceRange: [],
        dateRange: []
      }
    },

    // 设置分页参数
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 设置当前景区
    setCurrentScenic(scenic) {
      this.currentScenic = scenic
    },

    // 清空当前景区
    clearCurrentScenic() {
      this.currentScenic = null
    },

    // 获取景区分类选项
    getCategoryOptions() {
      return this.categories
    },

    // 添加新的景区分类
    addCategory(category) {
      if (!this.categories.find(cat => cat.value === category.value)) {
        this.categories.push(category)
      }
    }
  }
})